package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;
import model.User;
import model.UserDao;

import javax.jws.soap.SOAPBinding;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 1. 先根据博客 id 查找博客信息
 * 2. 根据 博客信息里面的作者 id 去查作者
 */
@WebServlet("/authorInfo")
public class AuthorServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       resp.setContentType("application/json;charset=utf8");
        // 通过这个方法，获取到指定的博客作者信息
        String param = req.getParameter("blogId");
        // 为空或者为空字符串
        if(param == null || "".equals(param)) {
            // 参数缺少了
            resp.getWriter().write("{\"ok\": false,\"reason\":\"参数缺失!：\" }");
            return;
        }

        // 根据当前 blogID 在数据库中进行查找，找到对应的 Blog 对象，再进一步的根据blog对象，找到作者信息

        // 分两步走，先去 blogDao 中去查找 blogId
        BlogDao blogDao = new BlogDao();
       Blog blog = blogDao.selectOne(Integer.parseInt(param));
       if(blog == null) {
           resp.getWriter().write("{\"ok\": false,\"reason\":\"要查询的博客不存在\" }");
           return;
       }

       // 根据 blog 对象，查找用户对象
        UserDao userDao = new UserDao();
       User author = userDao.selectById(blog.getUserId());
       if(author == null) {
           resp.getWriter().write("{\"ok\": false,\"reason\":\"要查询的用户不存在\" }");
           return;
       }

       // 把 author 对象 返回到浏览器
        // 注意要把密码给干掉
        author.setPassword("");
        resp.getWriter().write(objectMapper.writeValueAsString(author));
    }
}
